package com.tan.kotlintest.view

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ArgbEvaluator
import android.animation.ValueAnimator
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.RectF
import android.util.AttributeSet
import android.util.TypedValue
import android.view.View
import com.tan.kotlintest.R
import com.tan.kotlintest.util.LogUtil

class SwitchButton : View, View.OnClickListener {


    private var mSwitchViewBallColor: Int = 0
    private var mSwitchViewBgColor: Int = 0
    //圆形球的半径
    private var mBallRadius: Float = 0f
    //圆形球画笔
    private lateinit var mBallPaint: Paint
    //球的y值
    private var mBallXValue: Float = 0f
    //背景矩形框
    private lateinit var mBgStrokeRectF: RectF
    //背景画笔
    private lateinit var mBgPaint: Paint
    //当前状态
    private var mCurrentState: Int = CLOSE

    companion object {
        //关闭
        private const val CLOSE = 0
        //开启
        private const val OPEN = 1
    }

    constructor(context: Context) : super(context) {
        init(context, null, 0)
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        init(context, attrs, 0)
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init(context, attrs, defStyleAttr)
    }

    /**
     * 初始化
     */
    private fun init(context: Context, attrs: AttributeSet?, defStyleAttr: Int) {
        val typedArray = context.theme.obtainStyledAttributes(attrs, R.styleable.SwitchView, defStyleAttr, 0)
        val indexCount = typedArray.indexCount
        for (i in 0..indexCount) {
            when (val attr = typedArray.getIndex(i)) {
                R.styleable.SwitchView_switch_ball_color ->
                    mSwitchViewBallColor = typedArray.getColor(attr, Color.RED)
                R.styleable.SwitchView_switch_bg_color ->
                    mSwitchViewBgColor = typedArray.getColor(attr, Color.BLACK)
            }
        }
        typedArray.recycle()

        //初始化配置
        mBgPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        mBgPaint.color = mSwitchViewBgColor
        mBallPaint = Paint(Paint.ANTI_ALIAS_FLAG)
        mBallPaint.color = mSwitchViewBallColor

        //设置点击事件
        setOnClickListener(this)
    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        //初始化用于画图的矩形
        mBgStrokeRectF = RectF(0f, 0f, w.toFloat(), h.toFloat())
        //球和背景的间距等于高度的30分子1
        val strokeWidth = w.toFloat() / 30
        //半径等于 高度 - 间距 * 2
        mBallRadius = (h.toFloat() - strokeWidth * 2) / 2
        //球初始位置在左边,View高度的一半
        mBallXValue = h.toFloat() / 2
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        val widthMeasureMode = MeasureSpec.getMode(widthMeasureSpec)
        val heightMeasureMode = MeasureSpec.getMode(heightMeasureSpec)

        var width = 0
        var height = 0

        when (widthMeasureMode) {
            MeasureSpec.UNSPECIFIED ->
                width = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 70F, resources.displayMetrics).toInt()
            MeasureSpec.AT_MOST ->
                width = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 70F, resources.displayMetrics).toInt()
            MeasureSpec.EXACTLY ->
                width = MeasureSpec.getSize(widthMeasureSpec)
        }

        when (heightMeasureMode) {
            MeasureSpec.UNSPECIFIED ->
                height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30F, resources.displayMetrics).toInt()
            MeasureSpec.AT_MOST ->
                height = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 30F, resources.displayMetrics).toInt()
            MeasureSpec.EXACTLY ->
                height = MeasureSpec.getSize(heightMeasureSpec)
        }
        setMeasuredDimension(width, height)
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        //画椭圆背景
        canvas?.drawRoundRect(mBgStrokeRectF, height.toFloat() / 2, height.toFloat() / 2, mBgPaint)
        //画球
        canvas?.drawCircle(mBallXValue, height.toFloat() / 2, mBallRadius, mBallPaint)
    }

    override fun onClick(v: View?) {
        LogUtil.i("点击事件")
        //点击之后 开启动画
        if (mCurrentState == CLOSE) {
            mCurrentState = OPEN
            animateBall(true)
        } else {
            mCurrentState = CLOSE
            animateBall(false)
        }
    }

    /**
     * 动画
     */
    private fun animateBall(fromStartToEnd: Boolean) {
        val from: Float
        val to: Float
        val startColor: Int
        val endColor: Int
        if (fromStartToEnd) {
            from = height.toFloat() / 2
            to = width.toFloat() - height.toFloat() / 2
            startColor = mSwitchViewBgColor
            endColor = Color.BLUE
        } else {
            to = height.toFloat() / 2
            from = width.toFloat() - height.toFloat() / 2
            startColor = Color.BLUE
            endColor = mSwitchViewBgColor
        }

        //球平移动画
        val translateAnim = ValueAnimator.ofFloat(from, to)
        translateAnim.addUpdateListener {
            mBallXValue = it.animatedValue as Float
            postInvalidate()
        }

        //背景颜色动画
        val colorAnim = ValueAnimator.ofObject(ArgbEvaluator(), startColor, endColor)
        colorAnim.addUpdateListener {
            mBgPaint.color = it.animatedValue as Int
            postInvalidate()
        }

        //动画合集
        val animationSet = AnimatorSet()
        animationSet.playTogether(translateAnim, colorAnim)
        animationSet.duration = 200
        animationSet.addListener(object : Animator.AnimatorListener {
            override fun onAnimationRepeat(animation: Animator?) {
            }

            override fun onAnimationCancel(animation: Animator?) {
            }

            override fun onAnimationEnd(animation: Animator?) {
                isClickable = true
            }

            override fun onAnimationStart(animation: Animator?) {
                isClickable = false
            }

        })
        animationSet.start()
    }

}